<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/11 13:08:20 $)
// $RCSfile: client_tickets.php,v $ : $Revision: 1.23 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

define("VIEW_ASC", "1");
define("VIEW_DESC", "2");

require_once ("./modules/tickets/functions_ticketmain.php");
require_once ("./modules/tickets/functions_ticketcore.php");
require_once ("./modules/tickets/functions_clienttickets.php");
require_once ("./includes/functions_users.php");
require_once ("./includes/functions_customfields.php");
require_once ("./includes/functions_html.php");
require_once ("./includes/data_mimelist.php");
$template->loadLanguageSection("tickets_auditlogs", TEMPLATE_FILE);
$template->loadLanguageSection("tickets");

if (empty($_SWIFT["user"]["userid"]))
{
	$template->assign("errormessage", $_SWIFT["language"]["perminvalid"]);
	echo $template->displayTemplate("header");
	echo $template->displayTemplate("footer");
	exit;
}

$_useuserid = false;
if (defined("ISMODERNBILL"))
{
	$_useuserid = true;
}

/**
* ###############################################
* VIEW LIST
* ###############################################
*/
if ($eventaction == "viewlist")
{
	$template->cache(array('header', 'footer', 'navbar', 'ticketlist'));
	
	$sfields = array("ticketstatusid", "priorityid", "departmentid", "lastactivity", "lastreplier");
	//Mahesh Slaria: Sorting order......
	if (!empty($_REQUEST["sortby"]) && in_array($_REQUEST["sortby"], $sfields))
	{
		$_sortby = $_REQUEST["sortby"];
		//echo $_REQUEST["order"]. " Test <br>";
		$_order = iif(intval($_REQUEST["order"])==VIEW_ASC, "ASC", "DESC");
		//echo "ORDER" . $_order;
		
	}else {
		$_sortby = "lastactivity";
		$_order = "DESC";
	}
	//------------------------------------
	if (empty($_REQUEST["offset"]))
	{
		$_offset = 0;
	} else {
		$_offset = intval($_REQUEST["offset"]);
	}

	$_limit = intval($_SWIFT["settings"]["t_cperpage"]);
	if (empty($_limit))
	{
		$_limit = 8;
	}

	$_emaillist = getUserEmailList();

	$_ticketlist = array();
	$_total = 0;

	if ($_useuserid)
	{
		$_countarray = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."tickets` AS tickets WHERE `userid` = '". intval($_SWIFT["user"]["userid"]) ."';");
	} else {
		$_countarray = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."tickets` AS tickets WHERE `email` IN (". buildIN($_emaillist) .");");
	}
	if (empty($_countarray["totalitems"]))
	{
		$_total = 0;
	} else {
		$_total = intval($_countarray["totalitems"]);
	}
		$template->assign("sortby", $_sortby);
		$template->assign("oid", iif(intval($_REQUEST["order"])==VIEW_ASC, "2", "1"));
	$pagination = pagination(iif(defined("ISMODERNBILL"), "user.php?op=menu&tile=mysupport&_m=tickets&_a=viewlist", iif(empty($_REQUEST["sortby"]), "index.php?_m=tickets&_a=viewlist", "index.php?_m=tickets&_a=viewlist&sortby=".$_sortby."&order=".intval($_REQUEST["order"])."")), $_total, $_limit, $_offset, "5", "pageoftotal", TRUE, FALSE, TRUE);
	$template->assign("pagination", $pagination);
	$template->assign("offset", $_offset);
	$cnt = 0;

	if ($_useuserid)
	{
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."tickets` AS tickets WHERE `userid` = '". intval($_SWIFT["user"]["userid"]) ."' ORDER BY `". $dbCore->escape($_sortby) ."` ". $_order ." LIMIT ".intval($_offset).",".intval($_limit).";");
	} else {
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."tickets` AS tickets WHERE `email` IN (". buildIN($_emaillist) .") ORDER BY `". $dbCore->escape($_sortby) ."` ". $_order ." LIMIT ".intval($_offset).",".intval($_limit).";");
	}
	while ($dbCore->nextRecord())
	{
		$_ticketlist[$dbCore->Record["ticketid"]] = $dbCore->Record;
		$_ticket = &$_ticketlist[$dbCore->Record["ticketid"]];
		$_ticket["subject"] = htmlspecialchars($_ticket["subject"]);
		$_ticket["lastactivity"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $_ticket["lastactivity"]);
		$_ticket["status"] = iif($_SWIFT["statuscache"][$_ticket["ticketstatusid"]]["type"]=="private", $_SWIFT["statuscache"][$_ticket["ticketstatusid"]]["type"], $_SWIFT["statuscache"][$_ticket["ticketstatusid"]]["title"]);
		$_ticket["statuscolor"] = $_SWIFT["statuscache"][$_ticket["ticketstatusid"]]["statuscolor"];
		$_ticket["priority"] = $_SWIFT["prioritycache"][$_ticket["priorityid"]]["title"];
		$_ticket["prioritycolor"] = $_SWIFT["prioritycache"][$_ticket["priorityid"]]["frcolorcode"];
		$_ticket["department"] = iif($_SWIFT["departmentcache"][$_ticket["departmentid"]]["departmenttype"] == 'private', $_SWIFT["departmentcache"][$_ticket["departmentid"]]["departmenttype"], $_SWIFT["departmentcache"][$_ticket["departmentid"]]["title"]);
		$rowcolor = ($cnt%2)+1;
		$_ticket["fticketid"] = iif($_SWIFT["settings"]["t_eticketid"]=="seq",$_ticket["ticketid"], $_ticket["ticketmaskid"]);
		$_ticket["rowclass"] = "row".$rowcolor;

		$cnt++;
	}

	$template->assign("ticketlist", $_ticketlist);

	$template->assign("navigation", '<a href="'. iif(defined("ISMODERNBILL"), "user.php", "index.php") .'" id="navlink">'.$_SWIFT["language"]["navhome"].'</a> &raquo; <a href="'. iif(defined("ISMODERNBILL"), "user.php?op=menu&tile=mysupport&_m=tickets&_a=viewlist", "index.php?_m=tickets&_a=viewlist") .'" id="navlink">'.$_SWIFT["language"]["tticketlist"]."</a>");
	$template->assign("sectiontitle", $_SWIFT["language"]["tticketlist"]);
	$template->assign("sectiondesc", $_SWIFT["language"]["desc_tticketlist"]);
	$template->assign("backurl", iif(defined("ISMODERNBILL"), "user.php", "index.php"));

	echo $template->displayTemplate("ticketlist");






/**
* ###############################################
* VIEW TICKET
* ###############################################
*/
} else if ($eventaction == "viewticket") {
	// Load the ticket first
	$_ticketobj =& new TicketMain($_REQUEST["ticketid"], false);
	// Does this ticket belong to this user?
	if ((!$_useuserid && !in_array(strtolower($_ticketobj->ticket["email"]), getUserEmailList())) || ($_useuserid && $_ticketobj->ticket["userid"] != $_SWIFT["user"]["userid"]) || empty($_SWIFT["user"]["userid"]))
	{
		trigger_error($_SWIFT["language"]["vtnoaccess"], E_USER_ERROR);
		exit;
	}
	$_ticket = &$_ticketobj->ticket;
	$_ticket["subject"] = htmlspecialchars($_ticket["subject"]);


	// Update Custom Fields
	if ($_REQUEST["do"] == "update")
	{//Mahesh Slaria: Staff & user ticket creation
		if (checkCustomFieldContent(CUSTOMFIELD_USERTICKET, $_ticket["departmentid"]) || checkCustomFieldContent(CUSTOMFIELD_STAFFUSERTICKET, $_ticket["departmentid"])) {
			updateCustomFields(CUSTOMFIELD_USERTICKET, $_ticket["ticketid"], $_ticket["departmentid"], $_ticket["ticketid"]);
			//Mahesh Slaria: Staff & user ticket creation
			updateCustomFields(CUSTOMFIELD_STAFFUSERTICKET, $_ticket["ticketid"], $_ticket["departmentid"], $_ticket["ticketid"]);
			if (defined("ISMODERNBILL"))
			{
				header("location: user.php?op=menu&tile=mysupport&_m=tickets&_a=viewticket&ticketid=".intval($_ticket["ticketid"]));
			} else if (defined("ISMODERNBILLV5")) {
				global $CONF;
				header("location: helpdesk.php?action=". getActionID("ShowHelpdeskTicketDetails") ."&sid=". $CONF["user"]["sessionID"] ."&hdTicketID=".intval($_ticket["ticketid"]));
			} else {
				header("location: index.php?_m=tickets&_a=viewticket&ticketid=".intval($_ticket["ticketid"]));
			}
			exit;
		}

	// Update Properties
	} else if ($_POST["do"] == "updateprop" && !empty($_POST["ticketstatusid"]) && !empty($_POST["priorityid"])) {
		$_prioritylist = buildGroupPriorityList();

		if ($_POST["ticketstatusid"] != $_ticket["ticketstatusid"] && $_SWIFT["statuscache"][$_POST["ticketstatusid"]]["type"] == 'public') // Client Changed the Ticket Status
		{
			$_ticketobj->changeStatus($_POST["ticketstatusid"]);
		}

		if ($_POST["priorityid"] != $_ticket["priorityid"] && isset($_prioritylist[$_POST["priorityid"]]))
		{
			$_ticketobj->changePriority($_POST["priorityid"]);
		}
	}
	

	$_duetime = "";
	if ($_ticket["duetime"] != 0)
	{
		if (DATENOW >= $_ticket["duetime"])
		{
			// Overdue
			$_duetime = '<span class=\'tickettextred\'>'.$_SWIFT["language"]["overdue"].'</span>';
		} else {
			$_duetime = strColorDate(($_ticket["duetime"]-DATENOW), true);
		}
	}

	$_ticketobj->ticket["strduetime"] = $_duetime;
	$_ticketobj->ticket["ownername"] = $_SWIFT["staffcache"][$_ticket["ownerstaffid"]]["fullname"];

	$template->assign("tvstatus", iif($_SWIFT["statuscache"][$_ticket["ticketstatusid"]]["type"]=="private", $_SWIFT["statuscache"][$_ticket["ticketstatusid"]]["type"], $_SWIFT["statuscache"][$_ticket["ticketstatusid"]]["title"]));

	$template->assign("tvdepartment", iif($_SWIFT["departmentcache"][$_ticket["departmentid"]]["departmenttype"] == 'private', $_SWIFT["departmentcache"][$_ticket["departmentid"]]["departmenttype"], $_SWIFT["departmentcache"][$_ticket["departmentid"]]["title"]));

	$_ticketobj->loadTemplateVariables(true);

	if ($_SWIFT["user"]["permissions"]["perm_canchangepriorities"] == "0")
	{
		$template->assign("canchangeproperties", false);
	} else {
		$template->assign("canchangeproperties", true);
	}


	$cfrender = renderClientCustomFields(CUSTOMFIELD_USERTICKET, $_ticket["ticketid"], 0, $_ticket["ticketid"]);
	//Mahesh Slaria: Staff & user ticket creation
	$scfrender = renderClientCustomFields(CUSTOMFIELD_STAFFUSERTICKET, $_ticket["ticketid"], 0, $_ticket["ticketid"]);
	$template->assign("cfrender", array_merge($cfrender, $scfrender));

//	$template->assign("scfrender", $scfrender);

	if (count($cfrender) || count($scfrender))
	{
		$template->assign("hascustomfields", "1");
	}

	if (defined("ISMODERNBILLV5"))
	{
		global $CONF;
		$template->assign("navigation", '<a href="dashboard.php?action='. getActionID("ShowDashboard") .'&sid='. $CONF["user"]["sessionID"] .'" id="navlink">'.$_SWIFT["language"]["tticketlist"].'</a> &raquo; <a href="helpdesk.php?action='. getActionID("ShowHelpdeskTicketDetails") .'&sid='. $CONF["user"]["sessionID"] .'&hdTicketID='. intval($_ticketobj->ticket["ticketid"]) .'" id="navlink">'.$_ticket["fticketid"]."</a>");
		$template->assign("backurl", 'dashboard.php?action='. getActionID("ShowDashboard") .'&sid='. $CONF["user"]["sessionID"]);
		$template->assign("modernbill", array("actionid" => getActionID("ShowHelpdeskTicketDetails"), "editactionid" => getActionID("EditHelpdeskTicketResponse"), "sessionid" => $CONF["user"]["sessionID"]));
	} else {
		$template->assign("navigation", '<a href="'. iif(defined("ISMODERNBILL"), "user.php", "index.php") .'" id="navlink">'.$_SWIFT["language"]["navhome"].'</a> &raquo; <a href="'. iif(defined("ISMODERNBILL"), "user.php?op=menu&tile=mysupport&_m=tickets&_a=viewlist", "index.php?_m=tickets&_a=viewlist") .'" id="navlink">'.$_SWIFT["language"]["tticketlist"].'</a> &raquo; <a href="'. iif(defined("ISMODERNBILL"), 'user.php?op=menu&tile=mysupport&_m=tickets&_a=viewticket&ticketid='. intval($_ticket["ticketid"]), 'index.php?_m=tickets&_a=viewticket&ticketid='. intval($_ticket["ticketid"])) .'" id="navlink">'.$_ticket["fticketid"]."</a>");
		$template->assign("backurl", iif(defined("ISMODERNBILL"), "user.php?op=menu&tile=mysupport&_m=tickets&_a=viewlist", "index.php?_m=tickets&_a=viewlist"));
	}

	$template->assign("postlist", $_ticketobj->getTicketPosts(false, false, iif($_SWIFT["settings"]["t_cpostorder"]=="asc", "asc", "desc"), true));
	$template->assign("sectiontitle", $_ticket["subject"]);

	echo $template->displayTemplate("viewticket");






/**
* ###############################################
* POST REPLY
* ###############################################
*/
} else if ($eventaction == "postreply") {
	// Load the ticket first
	$_ticketobj =& new TicketMain($_REQUEST["ticketid"], false);
	// Does this ticket belong to this user?
	if ((!$_useuserid && !in_array(strtolower($_ticketobj->ticket["email"]), getUserEmailList())) || ($_useuserid && $_ticketobj->ticket["userid"] != $_SWIFT["user"]["userid"]) || empty($_SWIFT["user"]["userid"]))
	{
		trigger_error($_SWIFT["language"]["vtnoaccess"], E_USER_ERROR);
		exit;
	}
	$_ticket = &$_ticketobj->ticket;
	$_ticketobj->loadTemplateVariables();

	if ($_POST["step"] == "1")
	{
		if (trim($_POST["message"]) == "")
		{
			$template->assign("errormessage", $_SWIFT["language"]["requiredfieldempty"]);
		} else {
			$ticketpostiddata = $_ticketobj->createTicketPost(false, POST_CLIENT, $_SWIFT["user"]["userid"], 0, $_SWIFT["user"]["fullname"], $_SWIFT["user"]["primaryemail"], "", $_ticket["subject"], $_POST["message"], false, false, false);

			if ($_SWIFT["settings"]["t_cenattach"] == 1)
			{
				$_attachmentlist = array();
				$_ticketobj->processPostAttachments($ticketpostiddata[0], false, (new stdClass), $_attachmentlist);
			}

			if (defined("ISMODERNBILL"))
			{
				header("location: user.php?op=menu&tile=mysupport&_m=tickets&_a=viewticket&ticketid=".intval($_ticket["ticketid"]));
			} else if (defined("ISMODERNBILLV5")) {
				global $CONF;
				header("location: helpdesk.php?action=". getActionID("ShowHelpdeskTicketDetails") ."&sid=". $CONF["user"]["sessionID"] ."&hdTicketID=".intval($_ticket["ticketid"]));
			} else {
				header("location: index.php?_m=tickets&_a=viewticket&ticketid=".intval($_ticket["ticketid"]));
			}
			exit;
		}
	}

	$template->assign("navigation", '<a href="'. iif(defined("ISMODERNBILL"), "user.php", "index.php") .'" id="navlink">'.$_SWIFT["language"]["navhome"].'</a> &raquo; <a href="'. iif(defined("ISMODERNBILL"), "user.php?op=menu&tile=mysupport&_m=tickets&_a=viewlist", "index.php?_m=tickets&_a=viewlist") .'" id="navlink">'.$_SWIFT["language"]["tticketlist"].'</a> &raquo; <a href="'. iif(defined("ISMODERNBILL"), 'user.php?op=menu&tile=mysupport&_m=tickets&_a=viewticket&ticketid='. intval($_ticket["ticketid"]), 'index.php?_m=tickets&_a=viewticket&ticketid='. intval($_ticket["ticketid"])) .'" id="navlink">'.$_ticket["fticketid"].'</a> &raquo; <a href="'. iif(defined("ISMODERNBILL"), 'user.php?op=menu&tile=mysupport&_m=tickets&_a=postreply&ticketid='. intval($_ticket["ticketid"]), 'index.php?_m=tickets&_a=postreply&ticketid='. intval($_ticket["ticketid"])) .'" id="navlink">'.$_SWIFT["language"]["vtpostreply"].'</a>');
	$template->assign("backurl", iif(defined("ISMODERNBILL"), 'user.php?op=menu&tile=mysupport&_m=tickets&_a=viewticket&ticketid='. intval($_ticket["ticketid"]), 'index.php?_m=tickets&_a=viewticket&ticketid='. intval($_ticket["ticketid"])));
	$template->assign("sectiontitle", $_SWIFT["language"]["vtpostreply"]);

	echo $template->displayTemplate("postreply");




/**
* ###############################################
* DOWNLOAD ATTACHMENT
* ###############################################
*/
} else if ($eventaction == "getattachment") {
	$_ticketobj =& new TicketMain($_REQUEST["ticketid"], false);
	// Does this ticket belong to this user?
	if ((!$_useuserid && !in_array(strtolower($_ticketobj->ticket["email"]), getUserEmailList())) || ($_useuserid && $_ticketobj->ticket["userid"] != $_SWIFT["user"]["userid"]) || empty($_SWIFT["user"]["userid"]))
	{
		trigger_error($_SWIFT["language"]["vtnoaccess"], E_USER_ERROR);
		exit;
	}
	$_ticket = &$_ticketobj->ticket;

	if (!empty($_GET["attachmentid"]))
	{
		require_once ("./modules/tickets/functions_attachments.php");
		$_attach = new TicketAttachments();
		$_attach->dispatchAttachment($_GET["attachmentid"], $_ticket["ticketid"]);
		exit;
	}
}



?>